<template>
  <div class="app-container">

    <div class="">
      <div style="margin-bottom: 20px;">
        <el-input v-model="listQuery.keyword" placeholder="角色名称/备注" style="width: 250px;" class="filter-item"/>
        
        <el-button class="" type="primary" icon="el-icon-search" @click="getList">
          搜索
        </el-button>
        <el-button class="" style="margin-left: 10px;" type="warning" icon="el-icon-edit" @click="roletj">
          创建新的角色
        </el-button>
      </div>

      <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      >
      <el-table-column label="角色" prop="title" min-width="150px">  
      </el-table-column>

      <el-table-column label="备注" prop="remark" min-width="150px">  
      </el-table-column>

      <el-table-column label="创建时间" prop="create_time" min-width="150px">  
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" style="margin-right: 10px;" @click="rolebj(scope.$index)">
            编辑
          </el-button>

          <el-button size="mini" type="danger" @click="roledel(scope.row.id,scope.$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    </div>

    <el-dialog :title="data.id == '0' ? '添加角色' : '保存角色'" :visible.sync="createFormBox">
      <el-form ref="form" :model="data" label-width="120px" :rules="rules" style="margin-top: 20px;">
            <el-form-item label="角色名称" prop="title">
                <el-input v-model="data.title"></el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input v-model="data.remark"></el-input>
            </el-form-item>

            <el-form-item label="权限" prop="auth">
                <el-radio v-model="strictly" :label="true">父子不互相关联</el-radio>
                <el-radio v-model="strictly" :label="false">父子互相关联（用于全选）</el-radio>

                <el-tree 
                ref="tree"
                :data="authdata" 
                node-key="id" 
                :props="defaultProps" 
                :default-checked-keys='data.auth_ids'
                show-checkbox 
                :check-strictly="strictly"
                :render-content="renderContent"
                @node-click="handleNodeClick">
                </el-tree>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="rolesave()">
                <span v-if="data.id == 0">添加</span>
                <span v-if="data.id > 0">保存</span>
                </el-button>
            </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
       
      </div>
    </el-dialog>

    
  </div>
</template>
<style>
.is_menu{color: rgb(64, 158, 255);font-weight: bold;}
.create-form-title {font-size: 16px;font-weight: bold;margin: 20px 0;}
.create-form-des {font-size: 13px;color: #aaa;}
</style>
<script>
import { rolelist,roleadd,roleedit,roledel,authlist} from '@/api/auth'
import { MessageBox, Message } from 'element-ui'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'

export default {
  name: 'role-list',
  components: { },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      strictly: true,//父子不互相关联 true 是不关联
      defaultProps: {
        children: 'sons',
        label: 'title',
        id: 'id'
      },
      authdata:[],
      checked_auth_ids: [],
      /*authdata: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }],*/
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: "",//搜索
        sort: 'id_desc'//默认的排序
      },
      data: {
        id: 0,
        title:"",
        remark: "",
        auth_ids: [],
      },
      createFormBox: false,//创建表单盒子显示和隐藏
      dialogStatus: '',
      dialogPvVisible: false,
      pvData: [],
      rules: {
        title: [{ required: true, message: '角色名称不能为空', trigger: 'change' }],
      },
    }
  },
  created() {
    this.getList()
    this.getAuth()
  },
  methods: {
    handleNodeClick(data) {
       console.log(data);
    },
    renderContent(h, { node, data, store }) {
        let is_menu = data.is_menu;
        if (is_menu == 1) {
            var menu = <span class='is_menu'>{node.label}</span>;
        } else {
            var menu = <span>{node.label}</span>;
        }
        return (
          <span class="custom-tree-node">
            {menu}
          </span>);
    },
    getList() {
      this.listLoading = true
      rolelist(this.listQuery).then(response => {
          setTimeout(() => {
          this.listLoading = false
          }, 100)

          let code = response.code;
          let msg = response.msg;

          if (code == 200) {
            this.list = response.response;
          } else {
            this.$message({
              message: msg,
              type: 'error'
            });
          }
      }).catch(() => {
          this.listLoading = false
      });
    },
    //获得所有的权限
    getAuth(){
        authlist({type: 1}).then(response => {
            if (response.code == 200) {
              var authdata = this.authdata;
              var auth = response.response;
              auth.forEach(item => {
                const menu = {
                  title: item.title,
                  sons: item.sons,
                  id: item.id,
                  is_menu: item.is_menu,
                  pid: item.pid,
                  path: item.path,
                  sort: item.sort,
                  icon: item.icon,
                }
                authdata.push(menu)
              })
            }

            console.log(authdata);
        })
    },
    //点击创建角色按钮
    roletj() {
        this.createFormBox = true;
        this.data.id = 0;
        this.data.title = "";
        this.data.remark = "";
        this.data.auth_ids = [];
        //重置勾选选中的权限
        this.$nextTick(() => {
           this.$refs.tree.setCheckedKeys([]);
        });
    },
    //点击编辑角色按钮
    rolebj(index) {
        //this.data = this.list[index];
        var data = {
            'id': this.list[index]['id'],
            'title': this.list[index]['title'],
            'remark': this.list[index]['remark'],
            'auth_ids':  this.list[index]['auth_ids'],
        };
        this.data = data;

        //重新勾选选中的权限
        this.$nextTick(() => {
           this.$refs.tree.setCheckedKeys(this.list[index]['auth_ids']);
        });

        this.createFormBox = true;
    },
    //创建角色/修改角色(确认按钮)
    rolesave(){
        var id = this.data.id;
        this.data.auth_ids = this.$refs.tree.getCheckedKeys();

        this.$refs['form'].validate((valid) => {
            if (valid) {
                if (id == 0) {//创建角色
                    this.roleadd();
                } else  {//保存角色
                    this.roleedit();
                }
            }
        })
    },
    //创建角色
    roleadd(){
        roleadd(this.data).then((res) => {
            var code = res.code;
            var msg = res.msg;
            if (code == 200) {
                this.getList();
                this.$refs['form'].resetFields();
                this.$message.success(msg);
            } else {
                this.$message.error(msg);
            }
        })
    },
    //保存角色
    roleedit(){
        roleedit(this.data).then((res) => {
            var code = res.code;
            var msg = res.msg;
            if (code == 200) {
                this.getList();
                this.$message.success(msg);
            } else {
                this.$message.error(msg);
            }
        })
    },
    //删除角色
    roledel(id,index){
        this.$confirm('确定删除此角色吗？！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          roledel({id:id}).then(response => {
              var code = response.code;
              var msg = response.msg;
              if (code == 200) {
                  this.list.splice(index, 1)
                  this.total = this.total - 1;
                  this.$message({
                    message: msg,
                    type: 'success'
                  });
              } else {
                this.$message({
                  message: msg,
                  type: 'error'
                });
              }
          })
        });
    },
  }
}
</script>
